This tutorial shows a simple example on how to use: ObservableObject, @Published, @ObservedObject.
When Property marked as @Published is changed, body Property of any View that uses that Property will be redrawn.
So it has the same purpose as @State for struct.
@Published can be used only inside a Class that implements ObservableObject Protocol.
Instance of such Class must be flagged with @ObservedObject.
This tells SwiftUI that you actually want to observe this Object in order to use this feature.
As soon as the View is loaded Property name is changed to "Bill" and the View is redrawn with this new value.
ContentView.swift
import SwiftUI
class Person : ObservableObject {
@Published var name = "John"
}
struct ContentView: View {
@ObservedObject var person = Person()
var body: some View {
VStack {
Button("Button") { self.person.name = "Bill" } //Change name Propert in Class Instance
Text(person.name) //Change to name is detected and View is redrawn
TextField("Enter Name", text: $person.name) //Reference to person.
}
}
}